<script setup lang="ts">
import { defineAsyncComponent, type Component, onErrorCaptured } from 'vue'
import UserProfile from '@/components/UserProfile.vue'

const AsyncComponent = defineAsyncComponent<Component>(
  () =>
    new Promise((resolve) => {
      setTimeout(async () => {
        const mod = await import('@/components/AsyncContent.vue')
        resolve(mod)
      }, 2000)
    }),
)

onErrorCaptured((err, _, info) => {
  console.error('捕获到错误:', err)
  console.log('错误信息:', info)
  return false // 阻止错误继续传播
})
</script>

<template>
  <div class="suspense-container">
    <div>
      Suspense 是 Vue3
      提供的一个内置组件，用于处理异步组件和异步数据获取。它允许我们在等待异步操作完成时显示加载状态，并在出现错误时显示错误信息
    </div>
    <h2>一、异步组件处理</h2>
    <Suspense>
      <template #default>
        <AsyncComponent />
      </template>
      <template #fallback>
        <div class="loading">
          <div class="spinner"></div>
          <p>加载中...</p>
        </div>
      </template>
    </Suspense>
    <h2>二、异步数据获取</h2>
    <Suspense>
      <template #default>
        <UserProfile />
      </template>
      <template #fallback>
        <div class="loading">
          <div class="spinner"></div>
          <p>加载用户信息中...</p>
        </div>
      </template>
    </Suspense>
  </div>
</template>

<style scoped lang="scss">
.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
